﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using EuphoricNation.Util;

namespace EuphoricNation.Rewrite
{
    /// <summary>
    /// A route to a specific type of page
    /// </summary>
    public class Route
    {
        private string[] _brokenApartPath;
        private string _path;
        private string _filename;

        /// <summary>
        /// Path to match
        /// </summary>
        public string Path
        {
            get { return _path; }
        }

        /// <summary>
        /// Internal filename to display/run
        /// </summary>
        public string Filename
        {
            get { return _filename; }
        }

        /// <summary>
        /// Create a new route
        /// </summary>
        /// <param name="path">Path to match</param>
        /// <param name="filename">Filename to display/run</param>
        public Route(string path, string filename)
        {
            _path = path;
            _filename = filename;

            // Cache the broken apart path
            _brokenApartPath = _path.Split('/').TrimBlank();
        }

        /// <summary>
        /// Returns whether this route matches the specified path
        /// </summary>
        /// <param name="path">Path, broken apart by forward slases</param>
        /// <returns>Match length (number of matching path parts before going into variables)</returns>
        public int MatchesPath(ref string[] path)
        {
            int count = 0;
            int i = 0, len = path.Length;

            // If the parts lengths don't match, then the paths can't possibly match
            if (path.Length != _brokenApartPath.Length)
                return -1;

            for (; i < len; ++i)
            {
                if (path[i] == _brokenApartPath[i])
                    ++count;
            }

            return count;
        }

        /// <summary>
        /// Get the variables for this route
        /// </summary>
        /// <param name="path">Path to match</param>
        /// <returns>Variables</returns>
        public Dictionary<string, string> GetVariables(ref string[] path)
        {
            Dictionary<string, string> vars = new Dictionary<string, string>();
            int i = 0, len = path.Length;
            string varName, varValue;

            for (; i < len; ++i)
            {
                // Quick check to see if this is a variable
                if (_brokenApartPath[i][0] == '{')
                {
                    varName = HttpContext.Current.Server.UrlDecode(_brokenApartPath[i].Substring(1, _brokenApartPath[i].Length - 2));
                    varValue = path[i];

                    vars[varName] = HttpContext.Current.Server.UrlDecode(varValue);
                }
            }

            return vars;
        }
    }
}